﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using mediaPrime.TVServerProvider;
using TvControl;

namespace mediaPrime.TVServerPlugin.MediaPortal
{
    [ServiceContract]
    public interface ITVServerPluginService
    {
        [OperationContract]
        [FaultContract(typeof(FaultException))]
        bool Start(int channelId, string user, bool force);

        [OperationContract]
        [FaultContract(typeof(FaultException))]
        bool Stop(string user);

        [OperationContract]
        [FaultContract(typeof(FaultException))]
        string GetStreamingUrl(string user);

        [OperationContract]
        [FaultContract(typeof(FaultException))]
        List<TVServerChannelGroup> GetChannelGroups();

        [OperationContract]
        [FaultContract(typeof(FaultException))]
        List<TVServerChannel> GetChannelsOfGroup(string group);

        [OperationContract]
        [FaultContract(typeof(FaultException))]
        List<TVServerChannel> GetAllChannels();

        [OperationContract]
        [FaultContract(typeof(FaultException))]
        List<TVServerEPGData> GetEPGForChannel(string channel);

        [OperationContract]
        [FaultContract(typeof(FaultException))]
        void RestartTVServer();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class TVServerPluginService : ITVServerPluginService
    {
        private List<VirtualCard> vCards = new List<VirtualCard>();

        #region ITVServerPluginService Member

        public bool Start(int channelId, string user, bool force)
        {
            try
            {
                IUser tvServerUser = new User(user, false);
                VirtualCard vCard;

                var result = TVServerPlugin.Controller.StartTimeShifting(ref tvServerUser, channelId, out vCard, force);
                if (result == TvResult.Succeeded)
                    vCards.Add(vCard);

                return (result == TvResult.Succeeded);
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }

        public bool Stop(string user)
        {
            var vCard = vCards.Where(card => card.User.Name == user).FirstOrDefault();
            if (vCard != null)
            {
                try
                {
                    vCard.StopTimeShifting();
                    return true;
                }
                catch (Exception ex)
                {
                    throw new FaultException(ex.Message);
                }
            }
            else
                return false;
        }

        public string GetStreamingUrl(string user)
        {
            var vCard = vCards.Where(card => card.User.Name == user).FirstOrDefault();
            if (vCard != null)
            {
                try
                {
                    return vCard.RTSPUrl;
                }
                catch (Exception ex)
                {
                    throw new FaultException(ex.Message);
                }
            }
            else
                return null;
        }

        public void RestartTVServer()
        {
            try
            {
                TVServerPlugin.Controller.Restart();
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }

        public List<TVServerChannelGroup> GetChannelGroups()
        {
            var returnValue = new List<TVServerChannelGroup>();
            var groups = TvDatabase.ChannelGroup.ListAll();
            foreach (var group in groups)
            {
                returnValue.Add(new TVServerChannelGroup() { Id = group.IdGroup.ToString(), Name = group.GroupName });
            }
            return returnValue;
        }

        public List<TVServerEPGData> GetEPGForChannel(string channel)
        {
            var returnValue = new List<TVServerEPGData>();

            var c = TvDatabase.Channel.ListAll().Where(c2 => c2.DisplayName == channel).FirstOrDefault();


            if (c != null)
            {
                var program = c.ReferringProgram();
                foreach (var item in program)
                {
                    var epgData = new TVServerEPGData();

                    epgData.Title = item.Title;
                    epgData.Description = item.Description;
                    epgData.StartTime = item.StartTime;
                    epgData.EndTime = item.EndTime;
                    epgData.ChannelId = item.IdChannel.ToString();

                    returnValue.Add(epgData);
                }
            }

            return returnValue;
        }

        public List<TVServerChannel> GetChannelsOfGroup(string group)
        {
            var returnValue = new List<TVServerChannel>();

            var channels = TvDatabase.Channel.ListAll();
            foreach (var channel in channels)
            {
                if (channel.GroupNames.Contains(group))
                    returnValue.Add(new TVServerChannel() { Id = channel.IdChannel.ToString(), Name = channel.DisplayName });
            }

            return returnValue;
        }

        public List<TVServerChannel> GetAllChannels()
        {
            var returnValue = new List<TVServerChannel>();

            var channels = TvDatabase.Channel.ListAll();
            foreach (var channel in channels)
            {
                returnValue.Add(new TVServerChannel() { Id = channel.IdChannel.ToString(), Name = channel.DisplayName });
            }

            return returnValue;
        }

        #endregion
    }
}
